<template>
  <el-container class="main-container">
    <el-aside :width="isCollapse ? '64px' : 'auto'">
      <!-- Logo区域 -->
      <div class="logo-container">
        <img src="@/assets/logo.png" alt="logo" class="logo-img">
        <span v-show="!isCollapse" class="logo-text">云县金叶合作社</span>
      </div>
      <!-- 侧边栏菜单 -->
      <sidebar-menu ref="sidebar" :is-collapse="isCollapse" />
    </el-aside>

    <el-container class="right-container">
      <!-- 头部区域 -->
      <el-header height="60px" class="main-header">
        <div class="header-left">
          <el-button
              type="text"
              class="collapse-btn"
              @click="toggleSidebar"
          >
            <i :class="isCollapse ? 'el-icon-s-unfold' : 'el-icon-s-fold'"></i>
          </el-button>
          <span class="welcome-text">欢迎进入金叶合作社</span>
        </div>
        <div class="header-right">
          <global-search/>
          <el-badge is-dot class="notification-badge">
            <el-button
                type="text"
                icon="el-icon-bell"
                class="header-icon"
            />
          </el-badge>
          <el-dropdown trigger="click">
            <span class="user-dropdown">
              <el-avatar size="small" icon="el-icon-user" />
              <span class="username">{{ userInfo ? userInfo.realName : '未登录' }}</span>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item icon="el-icon-user" @click.native="handleUserInfo">个人信息</el-dropdown-item>
              <el-dropdown-item icon="el-icon-switch-button" divided @click.native="handleLogout">退出登录
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </el-header>

      <el-main class="main-content">
        <router-view />
      </el-main>
    </el-container>
  </el-container>
</template>

<script>
import SidebarMenu from '@/components/Sidebar.vue'
import GlobalSearch from '@/components/GlobalSearch.vue'
import {mapActions, mapState} from 'vuex'
import { getUserMenuTree } from '@/utils/auth'

export default {
  name: 'MainLayout',
  components: {
    SidebarMenu,
    GlobalSearch
  },
  data() {
    return {
      isCollapse: false
    }
  },
  computed: {
    ...mapState(['userInfo'])
  },
  async created() {
    // 如果没有菜单数据，重新获取
    if (!this.$store.state.menuTree.length) {
      try {
        const response = await getUserMenuTree()
        if (response.code === 200) {
          this.$store.commit('SET_MENU_TREE', response.data)
          this.$store.commit('SET_PERMISSIONS', response.data)
        }
      } catch (error) {
        console.error('获取菜单失败:', error)
        this.$message.error('获取菜单失败，请重新登录')
        this.$router.push('/login')
      }
    }
  },
  methods: {
    // 使用  Vuex 的 mapActions 映射 logout 方法
    ...mapActions(['logout']),
    async handleLogout() {
      try {
        // this.logout()的作用是清除vuex中的token，并调用后端登出接口（目前后端未实现）
        await this.logout()
        this.$message.success('已安全退出')
        this.$router.push('/login')
      } catch (error) {
        console.error('登出失败:', error)
        this.$message.error(error.message || '登出失败，请重试')
        // 如果登出失败，仍然强制跳转到登录页
        this.$router.push('/login')
      }
    },
    handleUserInfo() {
      this.$router.push('/main/user')
    },
    toggleSidebar() {
      this.isCollapse = !this.isCollapse
    }
  }
}
</script>

<style lang="scss" scoped>
.main-container {
  height: 100vh;
  overflow: hidden;

  .el-aside {
    height: 100%;
    overflow: hidden;
    background-color: #304156;
  }

  .right-container {
    height: 100vh;
    overflow: hidden;
    display: flex;
    flex-direction: column;
  }

  .logo-container {
    height: 60px;
    padding: 10px;
    background: #2b2f3a;
    display: flex;
    align-items: center;

    .logo-img {
      width: 32px;
      height: 32px;
      margin-right: 12px;
    }

    .logo-text {
      color: #fff;
      font-size: 16px;
      font-weight: 600;
      white-space: nowrap;
      overflow: hidden;
    }
  }

  .main-header {
    background-color: #fff;
    border-bottom: 1px solid #e6e6e6;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 20px;
    box-shadow: 0 1px 4px rgba(0,21,41,.08);
    flex-shrink: 0;

    .header-left {
      display: flex;
      align-items: center;

      .collapse-btn {
        font-size: 20px;
        padding: 0 15px;
        cursor: pointer;
        transition: all 0.3s;

        &:hover {
          color: #409EFF;
        }

        i {
          font-size: 20px;
        }
      }

      .welcome-text {
        font-size: 16px;
        color: #333;
        margin-left: 10px;
      }
    }

    .header-right {
      display: flex;
      align-items: center;
      gap: 20px;

      .header-search {
        width: 200px;
      }

      .header-icon {
        font-size: 20px;
        color: #666;
        padding: 0 8px;
      }

      .notification-badge {
        margin-right: 20px;
      }

      .user-dropdown {
        display: flex;
        align-items: center;
        cursor: pointer;

        .username {
          margin-left: 8px;
          color: #666;
        }
      }
    }
  }

  .main-content {
    flex: 1;
    overflow: auto;
    background-color: #f0f2f5;
    padding: 20px;
    position: relative;
    height: calc(100vh - 60px);
  }
}
</style>